package com.kma.ncpractice2013.auth;


import com.kma.ncpractice2013.facade.MailFacade;
import com.kma.ncpractice2013.facade.MailFacadeImpl;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.SecureRandom;
import java.sql.*;
import java.util.UUID;


/**
 * User: Viktor
 * Date: 10/9/13
 */
@WebServlet(name = "Registration")
public class RegistrationServlet extends HttpServlet {
    public static final int VALIDATION_OK = 0;
    public static final int USERNAME_NOT_UNIQUE = 1;
    public static final int SQL_EXCEPTION = 2;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=UTF-8");
        String login = request.getParameter("r_login");
        String pass = request.getParameter("r_password");
        String username = request.getParameter("r_username");
        String phone = request.getParameter("r_phone");


		Connection conn = null;

        try
        {
            Context ctx=new InitialContext();
            DataSource ds= null;
            ds = (DataSource)ctx.lookup("jdbc/security");
            conn =ds.getConnection();



            if (validateInfo(conn, login, pass)==VALIDATION_OK)
            {

                SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
                secureRandom.setSeed(System.currentTimeMillis());
                byte[] salt = new byte[32];
                String token = UUID.randomUUID().toString();
                secureRandom.nextBytes(salt);
                String stringSalt = DatatypeConverter.printHexBinary(salt);

                MailFacade mail=new MailFacadeImpl();
                String email = login;
                String subject = "Reservation System registration confirmation";
                String letter = "Click on the following link to confirm your registration.\n" +
                        "https://localhost:8181/ReservationSystem_WEB-1.0-SNAPSHOT/confirmation.jsp?token=" + token +               //fix path
                        "\nLink is valid for 1 day.";
                try
                {
                    mail.sendLetter(email, subject, letter);

                }
                catch (Exception e)
                {
                    out.print(e.getMessage());
                    return;
                }
                Date d = new Date(System.currentTimeMillis());
                PreparedStatement ps = conn.prepareStatement("INSERT INTO USERS (LOGIN, PASSWORD, NAME, PHONE, REGISTRATION_DATE, GROUP_ID, SALT, REGISTRATION_TOKEN) VALUES (?, ?, ?, ?, ?, 5, ?, ?)");
                ps.setString(1, login);
                ps.setString(2, Crypto.getHash(stringSalt, pass, "SHA-256"));
                ps.setString(3, username);
                ps.setString(4, phone);
                ps.setDate(5, d);
                ps.setString(6, stringSalt);
                ps.setString(7, token);
                ps.executeUpdate();

                out.print("Confirmation letter has been sent to "+login);
                out.println("<a href=\"login.jsp\">login</a>");
                //response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/login.jsp"));



            }
            else
            {

            response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/register.jsp?errcode=1"));
            }
        }
        catch(Exception e)
        {
            out.print(e.getMessage());
            return;
        }
	    finally
        {
	        try
	        {
		        conn.close();
	        } catch (Exception e)
	        {
		        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
		        response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/error.jsp"));
	        }
        }


    }
	private int validateInfo(Connection conn, String uname, String pass)
	{


		PreparedStatement ps = null;
		try
        {
			ps = conn.prepareStatement("select ID from USERS where LOGIN = ?");
			ps.setString(1, uname);
			ResultSet execute = ps.executeQuery();

			if(!execute.next()) return VALIDATION_OK;
		}
        catch (SQLException e) {
			return SQL_EXCEPTION;

		}
		return USERNAME_NOT_UNIQUE;
        //TODO: input validation



	}

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
